import React, { useState, useCallback } from 'react';
import { RoomStatus } from '../../../types/room';
// import { RoomStatusManager } from '../utils/RoomStatusManager';
import EnhancedStatusIndicator from './EnhancedStatusIndicator';
import styles from '../styles/StatusWorkflow.module.css';

interface StatusWorkflowProps {
  currentStatus: RoomStatus;
  roomId: string;
  roomNumber: string;
  date: string;
  onStatusChange: (newStatus: RoomStatus, reason?: string) => void;
  onClose: () => void;
  position?: { x: number; y: number };
}

interface StatusTransition {
  from: RoomStatus;
  to: RoomStatus;
  label: string;
  description: string;
  requiresReason: boolean;
  category: 'normal' | 'maintenance' | 'cleaning' | 'special';
  icon: string;
  estimatedTime?: string;
}

// 状态流转规则配置
const STATUS_TRANSITIONS: StatusTransition[] = [
  // 可用房间的状态流转
  {
    from: RoomStatus.AVAILABLE,
    to: RoomStatus.BOOKED,
    label: '预订房间',
    description: '客人预订此房间',
    requiresReason: false,
    category: 'normal',
    icon: '📅',
    estimatedTime: '即时',
  },
  {
    from: RoomStatus.AVAILABLE,
    to: RoomStatus.MAINTENANCE,
    label: '进入维护',
    description: '房间需要维护保养',
    requiresReason: true,
    category: 'maintenance',
    icon: '🔧',
    estimatedTime: '2-4小时',
  },
  {
    from: RoomStatus.AVAILABLE,
    to: RoomStatus.CLEANING,
    label: '开始清洁',
    description: '房间清洁整理',
    requiresReason: false,
    category: 'cleaning',
    icon: '🧹',
    estimatedTime: '30-60分钟',
  },

  // 预订房间的状态流转
  {
    from: RoomStatus.BOOKED,
    to: RoomStatus.OCCUPIED,
    label: '办理入住',
    description: '客人办理入住手续',
    requiresReason: false,
    category: 'normal',
    icon: '🔑',
    estimatedTime: '即时',
  },
  {
    from: RoomStatus.BOOKED,
    to: RoomStatus.AVAILABLE,
    label: '取消预订',
    description: '取消房间预订',
    requiresReason: true,
    category: 'normal',
    icon: '❌',
    estimatedTime: '即时',
  },

  // 入住房间的状态流转
  {
    from: RoomStatus.OCCUPIED,
    to: RoomStatus.CHECKED_OUT,
    label: '办理退房',
    description: '客人办理退房手续',
    requiresReason: false,
    category: 'normal',
    icon: '📤',
    estimatedTime: '即时',
  },

  // 退房房间的状态流转
  {
    from: RoomStatus.CHECKED_OUT,
    to: RoomStatus.DIRTY,
    label: '标记脏房',
    description: '房间需要清洁',
    requiresReason: false,
    category: 'cleaning',
    icon: '🧽',
    estimatedTime: '即时',
  },
  {
    from: RoomStatus.CHECKED_OUT,
    to: RoomStatus.CLEANING,
    label: '开始清洁',
    description: '立即开始清洁',
    requiresReason: false,
    category: 'cleaning',
    icon: '🧹',
    estimatedTime: '30-60分钟',
  },

  // 脏房的状态流转
  {
    from: RoomStatus.DIRTY,
    to: RoomStatus.CLEANING,
    label: '开始清洁',
    description: '开始清洁房间',
    requiresReason: false,
    category: 'cleaning',
    icon: '🧹',
    estimatedTime: '30-60分钟',
  },

  // 清洁中的状态流转
  {
    from: RoomStatus.CLEANING,
    to: RoomStatus.CLEANED,
    label: '清洁完成',
    description: '房间清洁完成',
    requiresReason: false,
    category: 'cleaning',
    icon: '✨',
    estimatedTime: '即时',
  },
  {
    from: RoomStatus.CLEANING,
    to: RoomStatus.INSPECTING,
    label: '开始查房',
    description: '清洁完成，开始查房',
    requiresReason: false,
    category: 'cleaning',
    icon: '🔍',
    estimatedTime: '10-15分钟',
  },

  // 已清洁的状态流转
  {
    from: RoomStatus.CLEANED,
    to: RoomStatus.AVAILABLE,
    label: '恢复可用',
    description: '房间恢复可预订状态',
    requiresReason: false,
    category: 'normal',
    icon: '✅',
    estimatedTime: '即时',
  },
  {
    from: RoomStatus.CLEANED,
    to: RoomStatus.INSPECTING,
    label: '开始查房',
    description: '质检查房',
    requiresReason: false,
    category: 'cleaning',
    icon: '🔍',
    estimatedTime: '10-15分钟',
  },

  // 查房中的状态流转
  {
    from: RoomStatus.INSPECTING,
    to: RoomStatus.AVAILABLE,
    label: '查房通过',
    description: '查房合格，恢复可用',
    requiresReason: false,
    category: 'normal',
    icon: '✅',
    estimatedTime: '即时',
  },
  {
    from: RoomStatus.INSPECTING,
    to: RoomStatus.CLEANING,
    label: '重新清洁',
    description: '查房不合格，重新清洁',
    requiresReason: true,
    category: 'cleaning',
    icon: '🔄',
    estimatedTime: '30-60分钟',
  },

  // 维护相关状态流转
  {
    from: RoomStatus.MAINTENANCE,
    to: RoomStatus.AVAILABLE,
    label: '维护完成',
    description: '维护完成，恢复可用',
    requiresReason: false,
    category: 'maintenance',
    icon: '✅',
    estimatedTime: '即时',
  },
  {
    from: RoomStatus.MAINTENANCE,
    to: RoomStatus.REPAIR,
    label: '需要维修',
    description: '发现需要维修的问题',
    requiresReason: true,
    category: 'maintenance',
    icon: '🔨',
    estimatedTime: '4-8小时',
  },

  // 维修的状态流转
  {
    from: RoomStatus.REPAIR,
    to: RoomStatus.AVAILABLE,
    label: '维修完成',
    description: '维修完成，恢复可用',
    requiresReason: false,
    category: 'maintenance',
    icon: '✅',
    estimatedTime: '即时',
  },

  // 特殊状态流转
  {
    from: RoomStatus.OUT_OF_ORDER,
    to: RoomStatus.MAINTENANCE,
    label: '开始维护',
    description: '开始故障维护',
    requiresReason: true,
    category: 'maintenance',
    icon: '🔧',
    estimatedTime: '根据情况',
  },
];

const StatusWorkflow: React.FC<StatusWorkflowProps> = ({
  currentStatus,
  roomId: _roomId,
  roomNumber,
  date,
  onStatusChange,
  onClose,
  position = { x: 0, y: 0 },
}) => {
  const [selectedTransition, setSelectedTransition] =
    useState<StatusTransition | null>(null);
  const [reason, setReason] = useState('');
  const [showReasonDialog, setShowReasonDialog] = useState(false);

  // 获取当前状态可用的流转选项
  const availableTransitions = STATUS_TRANSITIONS.filter(
    transition => transition.from === currentStatus
  );

  // 按分类分组流转选项
  const groupedTransitions = availableTransitions.reduce(
    (groups, transition) => {
      if (!groups[transition.category]) {
        groups[transition.category] = [];
      }
      groups[transition.category].push(transition);
      return groups;
    },
    {} as Record<string, StatusTransition[]>
  );

  const categoryLabels = {
    normal: '🏨 常规操作',
    cleaning: '🧹 清洁流程',
    maintenance: '🔧 维护维修',
    special: '⚠️ 特殊操作',
  };

  const handleTransitionClick = useCallback(
    (transition: StatusTransition) => {
      if (transition.requiresReason) {
        setSelectedTransition(transition);
        setShowReasonDialog(true);
      } else {
        onStatusChange(transition.to);
      }
    },
    [onStatusChange]
  );

  const handleConfirmWithReason = useCallback(() => {
    if (selectedTransition) {
      onStatusChange(selectedTransition.to, reason);
      setShowReasonDialog(false);
      setSelectedTransition(null);
      setReason('');
    }
  }, [selectedTransition, reason, onStatusChange]);

  const handleCancelReason = useCallback(() => {
    setShowReasonDialog(false);
    setSelectedTransition(null);
    setReason('');
  }, []);

  if (availableTransitions.length === 0) {
    return (
      <div
        className={styles.workflowContainer}
        style={{ left: position.x, top: position.y }}
      >
        <div className={styles.header}>
          <h3>状态流转</h3>
          <button className={styles.closeButton} onClick={onClose}>
            ×
          </button>
        </div>
        <div className={styles.noTransitions}>
          <span>🔒</span>
          <p>当前状态无可用操作</p>
        </div>
      </div>
    );
  }

  return (
    <>
      <div
        className={styles.workflowContainer}
        style={{ left: position.x, top: position.y }}
      >
        <div className={styles.header}>
          <div className={styles.headerInfo}>
            <h3>状态流转</h3>
            <span className={styles.roomInfo}>
              {roomNumber} - {date}
            </span>
          </div>
          <button className={styles.closeButton} onClick={onClose}>
            ×
          </button>
        </div>

        <div className={styles.currentStatus}>
          <span className={styles.currentStatusLabel}>当前状态：</span>
          <EnhancedStatusIndicator
            status={currentStatus}
            size='medium'
            showIcon={true}
            showLabel={true}
          />
        </div>

        <div className={styles.transitionsContainer}>
          {Object.entries(groupedTransitions).map(([category, transitions]) => (
            <div key={category} className={styles.categoryGroup}>
              <h4 className={styles.categoryLabel}>
                {categoryLabels[category as keyof typeof categoryLabels]}
              </h4>
              <div className={styles.transitionsList}>
                {transitions.map((transition, index) => (
                  <button
                    key={index}
                    className={styles.transitionButton}
                    onClick={() => handleTransitionClick(transition)}
                    data-category={category}
                  >
                    <div className={styles.transitionIcon}>
                      {transition.icon}
                    </div>
                    <div className={styles.transitionContent}>
                      <div className={styles.transitionLabel}>
                        {transition.label}
                      </div>
                      <div className={styles.transitionDescription}>
                        {transition.description}
                      </div>
                      {transition.estimatedTime && (
                        <div className={styles.estimatedTime}>
                          ⏱️ {transition.estimatedTime}
                        </div>
                      )}
                    </div>
                    <div className={styles.transitionArrow}>
                      <EnhancedStatusIndicator
                        status={transition.to}
                        size='small'
                        showIcon={true}
                        showLabel={false}
                      />
                    </div>
                    {transition.requiresReason && (
                      <div className={styles.requiresReason}>📝</div>
                    )}
                  </button>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 原因输入对话框 */}
      {showReasonDialog && selectedTransition && (
        <div className={styles.reasonDialog}>
          <div className={styles.reasonDialogContent}>
            <h4>请输入操作原因</h4>
            <p>
              {selectedTransition.label}: {selectedTransition.description}
            </p>
            <textarea
              className={styles.reasonInput}
              value={reason}
              onChange={e => setReason(e.target.value)}
              placeholder='请输入详细原因（必填）...'
              rows={3}
              autoFocus
            />
            <div className={styles.reasonActions}>
              <button
                className={styles.confirmButton}
                onClick={handleConfirmWithReason}
                disabled={!reason.trim()}
              >
                确认操作
              </button>
              <button
                className={styles.cancelButton}
                onClick={handleCancelReason}
              >
                取消
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default StatusWorkflow;
